# coding:utf-8

import MySQLdb
import json 

def parserTpl(dictData, tplName):
  f=open(tplName)
  data=f.read()
  pos=0
  state=0
  tplkeys=list()
  while pos<len(data):
    tp1 = data.find("{{", pos)
    if tp1 < 0:
      break
    tp2 = data.find("}}", tp1)
    key=data[tp1+2:tp2]
    if key not in tplkeys:
      tplkeys.append(key.strip())
    pos = tp2+2
    #print "'"+key.strip()+"'"
  res = data
  for i in tplkeys:
    dst=""
    if i in dictData:
      dst=dictData[i]
    res=res.replace("{{%s}}"%(i), dst) 
  print res;


def expandStock(code):
  conn=MySQLdb.connect(host="10.241.84.65",user="root",db="stock")
  cursor = conn.cursor()
  sql = "select curprice,detail,name from stock_info where code='%s'"%(code)
  cursor.execute(sql)
  rows = cursor.fetchall()
  curprice=rows[0][0]
  jo=json.loads(rows[0][1])
  dictData = dict()
  for i in jo:
    dictData[i.strip().encode("UTF-8")] = jo[i].strip().encode("UTF-8")
  
  dictData["流通市值(亿)："] = "%.2f" % (float(dictData["流通股本(万股)："].replace(",",""))*curprice/10000)
  dictData["总市值(亿)："] = "%.2f" % (float(dictData["总股本(万股)："].replace(",",""))*curprice/10000)
  dictData["stockname"] = "%s(%s)" % (rows[0][2],code)

  parserTpl(dictData, "stockpanel.tpl")

expandStock('600031');

